<?php
/**
 * Created by PhpStorm.
 * User: JHR
 * Date: 2019/3/19
 * Time: 13:45
 */
namespace app\manage\controller;
use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use think\Db;
use my\Kuaidiniao;

class Food extends Base {
//商品列表
    public function foodList() {
        $param['search'] = input('post.search');
        $param['shop_id'] = input('post.shop_id');
        $param['cate_id'] = input('post.cate_id');
        $curr_page = input('post.pageIndex',1);
        $perpage = input('post.pageSize',10);
        $where = [
            ['f.del','=',0],
            ['s.del','=',0]
        ];
        if($param['shop_id']) {
            $where[] = ['f.shop_id','=',$param['shop_id']];
        }
        if($param['cate_id']) {
            $where[] = ['f.cate_id','=',$param['cate_id']];
        }
        if($param['search']) {
            $where[] = ['f.food_name','like',"%{$param['search']}%"];
        }
        if($this->userinfo['admin_id'] !== 1) {
            $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
            $where[] = ['f.shop_id','in',$shop_ids];
        }
        try {
            $count = Db::table('mp_food')->alias('f')
                ->join('mp_shop s','f.shop_id=s.id','left')
                ->where($where)->count();
            $page['count'] = $count;
            $page['curr'] = $curr_page;
            $page['totalPage'] = ceil($count/$perpage);
            $list = Db::table('mp_food')->alias('f')
                ->join('mp_food_cate c','f.cate_id=c.id','left')
                ->join('mp_shop s','f.shop_id=s.id','left')
                ->where($where)
                ->limit(($curr_page - 1)*$perpage,$perpage)
                ->order(['f.id'=>'DESC'])
                ->field('f.*,c.cate_name,s.shop_name')
                ->select();
        }catch (\Exception $e) {
            return ajax('SQL错误: ' . $e->getMessage(),-1);
        }
        foreach ($list as &$v) {
            $v['pic'] = json_decode($v['pics'],true)[0];
            unset($v['pics']);
        }
        $ret = [
            'food_list' => $list,
            'page' => $page
        ];
        return ajax($ret);
    }
//商品详情
    public function foodDetail() {
        $post['food_id'] = input('post.food_id');
        checkPost($post);
        try {
            $whereFood = [
                ['id','=',$post['food_id']],
                ['del','=',0]
            ];
            $info = Db::table('mp_food')->where($whereFood)->find();
            if(!$info) {
                return ajax($post['food_id'],-4);
            }
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        $info['pics'] = json_decode($info['pics'],true);
        return ajax($info);
    }
//添加商品POST
    public function foodAdd() {
        $post['shop_id'] = input('post.shop_id');
        $post['cate_id'] = input('post.cate_id');
        $post['food_name'] = input('post.food_name');
        $post['price'] = input('post.price');
        $post['origin_price'] = input('post.origin_price');
        $post['stock'] = input('post.stock');
        $post['status'] = input('post.status');
        checkPost($post);
        $post['detail'] = input('post.detail');
        $post['raw'] = input('post.raw');
        $post['weight'] = input('post.weight');
        $post['price_desc'] = input('post.price_desc');
        $time = time();
        $post['create_time'] = $time;
        $image = input('post.path',[]);
        try {
            if($this->userinfo['admin_id'] !== 1) {
                $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
                if(!in_array($post['shop_id'],$shop_ids)) {
                    return ajax($post,-4);
                }
            }
            $whereCate = [
                'shop_id' => $post['shop_id'],
                'id' => $post['cate_id']
            ];
            $cate_exist = Db::table('mp_food_cate')->where($whereCate)->find();
            if(!$cate_exist) {
                return ajax($whereCate,-4);
            }
            $whereFood = [
                ['del','=',0],
                ['shop_id','=',$post['shop_id']]
            ];
            $food_num = Db::table('mp_food')->where($whereFood)->count('id');
            if($food_num >= 100) {
                return ajax('已达限制数量, 无法添加',41);
            }
            $image_array = [];
            $limit = 6;
            if(is_array($image) && !empty($image)) {
                if(count($image) > $limit) {
                    return ajax('最多上传'.$limit.'张图片',71);
                }
                foreach ($image as $v) {
                    $oss_exist = $this->existObject($v);
                    if($oss_exist !== true) {
                        return ajax('图片已失效请重新上传',70);
                    }
                }
            }else {
                return ajax('请上传图片',3);
            }
            foreach ($image as $v) {
                $image_move = $this->moveObject($v,'upload/food/');
                if($image_move['code'] == 0) {
                    $image_array[] = $image_move['path'];
                }else {
                    return ajax('OSS异常',72);
                }
            }
            $post['pics'] = json_encode($image_array);
            Db::table('mp_food')->insertGetId($post);
        }catch (\Exception $e) {
            foreach ($image_array as $v) {
                $this->deleteObject($v);
            }
            return ajax($e->getMessage(),-1);
        }
        return ajax([],1);
    }
//修改商品POST
    public function foodMod() {
        $post['shop_id'] = input('post.shop_id');
        $post['cate_id'] = input('post.cate_id');
        $post['food_name'] = input('post.food_name');
        $post['price'] = input('post.price');
        $post['origin_price'] = input('post.origin_price');
        $post['stock'] = input('post.stock');
        $post['status'] = input('post.status');
        $post['id'] = input('post.food_id');
        checkPost($post);
        $post['detail'] = input('post.detail');
        $post['raw'] = input('post.raw');
        $post['weight'] = input('post.weight');
        $post['price_desc'] = input('post.price_desc');
        $time = time();
        $post['create_time'] = $time;
        $image = input('post.path',[]);
        try {
            if($this->userinfo['admin_id'] !== 1) {
                $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
                if(!in_array($post['shop_id'],$shop_ids)) {
                    return ajax($post,-4);
                }
            }
            $whereCate = [
                'shop_id' => $post['shop_id'],
                'id' => $post['cate_id']
            ];
            $cate_exist = Db::table('mp_food_cate')->where($whereCate)->find();
            if(!$cate_exist) {
                return ajax($whereCate,-4);
            }
            $map = [
                ['id','=',$post['id']],
                ['del','=',0]
            ];
            $goods_exist = Db::table('mp_food')->where($map)->find();
            if(!$goods_exist) {
                return ajax('food_id',-4);
            }
            $old_pics = json_decode($goods_exist['pics'],true);
            $image_array = [];
            $limit = 6;
            if(is_array($image) && !empty($image)) {
                if(count($image) > $limit) {
                    return ajax('最多上传'.$limit.'张图片',71);
                }
                foreach ($image as $v) {
                    $oss_exist = $this->existObject($v);
                    if($oss_exist !== true) {
                        return ajax('图片已失效请重新上传',70);
                    }
                }
            }else {
                return ajax('请上传图片',3);
            }
            foreach ($image as $v) {
                $image_move = $this->moveObject($v,'upload/food/');
                if($image_move['code'] == 0) {
                    $image_array[] = $image_move['path'];
                }else {
                    return ajax('OSS异常',72);
                }
            }
            $post['pics'] = json_encode($image_array);
            Db::table('mp_food')->where($map)->update($post);

        }catch (\Exception $e) {
            foreach ($image_array as $v) {
                if(!in_array($v,$old_pics)) {
                    $this->deleteObject($v);
                }
            }
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }
    //删除商品...
    public function foodDelete() {
        $post['food_id'] = input('post.food_id','');
        checkPost($post);
        $where = [
            ['id','=',$post['food_id']]
        ];
        try {
            if($this->userinfo['admin_id'] !== 1) {
                $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
                $where[] = ['shop_id','in',$shop_ids];
            }
            Db::table('mp_food')->where($where)->update(['del'=>1]);
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    //推荐
    public function foodRecommend() {
        $id = input('post.id','0');
        $where = [
            ['id','=',$id]
        ];
        try {
            if($this->userinfo['admin_id'] !== 1) {
                $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
                $where[] = ['shop_id','in',$shop_ids];
            }
            $goods_exist = Db::table('mp_food')->where($where)->find();
            if($goods_exist['recommend'] == 1) {
                Db::table('mp_food')->where($where)->update(['recommend'=>0]);
                return ajax(0);
            }else {
                Db::table('mp_food')->where($where)->update(['recommend'=>1]);
                return ajax(1);
            }
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }

    }
    //上架下架
    public function foodStatus() {
        $id = input('post.id','0');
        $where = [
            ['id','=',$id]
        ];
        try {
            if($this->userinfo['admin_id'] !== 1) {
                $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
                $where[] = ['shop_id','in',$shop_ids];
            }
            $goods_exist = Db::table('mp_food')->where($where)->find();
            if($goods_exist['status'] == 1) {
                Db::table('mp_food')->where($where)->update(['status'=>0]);
                return ajax(0);
            }else {
                Db::table('mp_food')->where($where)->update(['status'=>1]);
                return ajax(1);
            }
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
    }
    //商品排序
    public function sortGoods() {
        $post['id'] = input('post.id');
        $post['sort'] = input('post.sort');
        checkInput($post);
        try {
            $where = [
                ['id','=',$post['id']]
            ];
            if($this->userinfo['admin_id'] !== 1) {
                $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
                $where[] = ['shop_id','in',$shop_ids];
            }
            Db::table('mp_food')->where($where)->update($post);
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }
//分类列表
    public function cateList() {
        $curr_page = input('post.pageIndex',1);
        $perpage = input('post.pageSize',10);
        $post['shop_id'] = input('post.shop_id');
        checkPost($post);

        $where = [
            ['del','=',0],
        ];
        if($post['shop_id'] !== 'all') {
            $where[] = ['shop_id','=',$post['shop_id']];
        }
        if($this->userinfo['admin_id'] !== 1) {
            $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
            $where[] = ['shop_id','in',$shop_ids];
        }
        try {
            $count = Db::table('mp_food_cate')->where($where)->count();
            $list = Db::table('mp_food_cate')->where($where)
                ->order(['id'=>'DESC'])
                ->limit(($curr_page - 1)*$perpage,$perpage)->select();
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        $ret = [
            'count' => $count,
            'list' => $list
        ];
        return ajax($ret);
    }
//添加分类
    public function cateAdd() {
        $post['shop_id'] = input('post.shop_id');
        $post['cate_name'] = input('post.cate_name');
        $post['status'] = input('post.status');
        checkPost($post);
        try {
            if($this->userinfo['admin_id'] !== 1) {
                $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
                if(!in_array($post['shop_id'],$shop_ids)) {
                    return ajax($post,-4);
                }
            }
            $whereShop = [
                ['id','=',$post['shop_id']],
                ['del','=',0],
            ];
            $shop = Db::table('mp_shop')->where($whereShop)->find();
            if(!$shop) {
                return ajax($post,-4);
            }
            $whereCate = [
                ['del','=',0],
                ['shop_id','=',$post['shop_id']]
            ];
            $cate_num = Db::table('mp_food_cate')->where($whereCate)->count('id');
            if($cate_num >= 20) {
                return ajax('已达限制数量, 无法添加',41);
            }
            Db::table('mp_food_cate')->insert($post);
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }
//分类详情
    public function cateDetail() {
        $post['id'] = input('post.id','');
        try {
            $whereCate = [
                ['id','=',$post['id']]
            ];
            $info = Db::table('mp_food_cate')->where($whereCate)->find();
            if(!$info) {
                return ajax('非法参数',-4);
            }
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax($info);
    }
//修改分类POST
    public function cateMod() {
        $post['shop_id'] = input('post.shop_id');
        $post['cate_name'] = input('post.cate_name');
        $post['status'] = input('post.status');
        $post['id'] = input('post.id');
        checkPost($post);
        try {
            if($this->userinfo['admin_id'] !== 1) {
                $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
                if(!in_array($post['shop_id'],$shop_ids)) {
                    return ajax($post,-4);
                }
            }
            $whereCate = [
                ['id','=',$post['id']]
            ];
            $cate_exist = Db::table('mp_food_cate')->where($whereCate)->find();
            if(!$cate_exist) {
                return ajax('非法参数',-4);
            }
            $whereShop = [
                ['id','=',$post['shop_id']],
                ['del','=',0],
            ];
            $shop = Db::table('mp_shop')->where($whereShop)->find();
            if(!$shop) {
                return ajax($post,-4);
            }
            Db::table('mp_food_cate')->where($whereCate)->update($post);
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }
//删除分类
    public function cateDelete() {
        $post['id'] = input('post.id');
        try {
            $whereCate = [
                ['id','=',$post['id']]
            ];
            if($this->userinfo['admin_id'] !== 1) {
                $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
                $whereCate[] = ['shop_id','in',$shop_ids];
            }
            $exist = Db::table('mp_food_cate')->where($whereCate)->find();
            if(!$exist) {
                return ajax('非法参数',-1);
            }
            Db::table('mp_food_cate')->where($whereCate)->update(['del'=>1]);
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }

    //订单列表
    public function orderList() {
        $type = input('post.type','');
        $status = input('post.status','');
        $search = input('post.search','');
        $curr_page = input('post.pageIndex',1);
        $perpage = input('post.pageSize',10);
        $date = input('post.date',[]);
        $whereOrder = [
            ['o.del','=',0]
        ];
        if(!empty($date)) {
            $whereOrder[] = ['o.create_time','>',strtotime($date[0])];
            $whereOrder[] = ['o.create_time','<',strtotime($date[1] . ' 23:59:59')];
        }
        if($search) {
            $whereOrder[] = ['o.pay_order_sn','like',"%{$search}%"];
        }
        if($status !== '') {
            switch ($status) {
                case '0':
                    $whereOrder[] = ['o.status','=',0];
                    break;
                case '1':
                    $whereOrder[] = ['o.status','=',1];
                    break;
                case '2':
                    $whereOrder[] = ['o.refund','=',2];
                    break;
            }
        }
        if($type !== '') {
            $whereOrder[] = ['o.type','=',$type];
        }
        try {
            if($this->userinfo['admin_id'] !== 1) {
                $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
                $whereOrder[] = ['o.shop_id','in',$shop_ids];
            }
            $count = Db::table('mp_food_order')->alias('o')->where($whereOrder)->count();
            $order_list = Db::table('mp_food_order')->alias('o')
                ->where($whereOrder)
                ->order(['o.id'=>'DESC'])
                ->limit(($curr_page - 1)*$perpage,$perpage)
                ->field('id,pay_order_sn,pay_price,status,refund,shop_name,table_no,number,is_print,create_time,pay_time,refund_time,type')
                ->select();
            if(!empty($order_list)) {
                $order_ids = [];
                foreach ($order_list as $order) {
                    $order_ids[] = $order['id'];
                }
                $whereDetail = [
                    ['order_id','in',$order_ids]
                ];
                $detail_list = Db::table('mp_food_order')->alias('o')
                    ->join('mp_food_order_detail d','o.id=d.order_id','left')
                    ->field('d.order_id,d.food_id,d.food_name,d.num,d.unit_price,d.total_price,d.pic')
                    ->where($whereDetail)
                    ->select();
            }else {
                $detail_list = [];
            }
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        $ret = [
            'order_list' => $order_list,
            'detail_list' => $detail_list,
            'count' => $count
        ];
        return ajax($ret);
    }
    //退款
    public function orderRefund() {
        $post['pay_order_sn'] = input('post.pay_order_sn');
        checkPost($post);
        $out_refund_no = 'r' . create_unique_number();
        $pay_order_sn = $post['pay_order_sn'];
        try {
            $whereOrder = [
                ['pay_order_sn','=',$pay_order_sn]
            ];
            $order_exist = Db::table('mp_food_order')->where($whereOrder)->find();
            if(!$order_exist) {
                return ajax('订单不存在',27);
            }
            if($this->userinfo['admin_id'] !== 1) {
                $shop_ids = $this->getMyShopIds($this->userinfo['admin_id']);
                if(!in_array($order_exist['shop_id'],$shop_ids)) {
                    return ajax($post,-4);
                }
            }
            if($order_exist['status'] != 1) {
                return ajax('订单当前状态无法退款',40);
            }
            if($order_exist['type'] == 1) {
                $options = [
                    'appid' => config('appid'),
                    'mch_id'=> config('mch_id'),
                    'nonce_str'=>randomkeys(32),
                    'sign_type'=>'MD5',
                    'transaction_id'=> $order_exist['trans_id'],
                    'out_trade_no'=> $pay_order_sn,
                    'out_refund_no'=> $out_refund_no,
                    'total_fee'=> floatval($order_exist['pay_price'])*100,
                    'refund_fee'=> floatval($order_exist['pay_price'])*100,
                    'refund_fee_type'=> 'CNY',
                    'refund_desc'=> '商品无货',
                    'notify_url'=> $_SERVER['REQUEST_SCHEME'] . '://'.$_SERVER['HTTP_HOST'].'/api/wechatpay/refund_notify',
                    'refund_account' => 'REFUND_SOURCE_UNSETTLED_FUNDS'
                ];
                $options['sign'] = getSign($options,config('mch_key'));
                $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
                $res = curl_post_data($url,array2xml($options),true);
                $result = xml2array($res);
                mylog($this->cmd, var_export($result, true), 'wx_refund.log');
                if($result && $result['return_code'] == 'SUCCESS') {
                    if($result['result_code'] == 'SUCCESS') {
                        Db::table('mp_food_order')->where($whereOrder)->update([
                            'refund' => 2,
                            'refund_no' => $out_refund_no,
                            'refund_apply_time' => time(),
                            'refund_time' => time()
                        ]);
                    }else {
                        return ajax($result['err_code_des'],-1,$result['err_code_des']);
                    }
                }else {
                    return ajax('退款失败',-1);
                }
            }else {
                $options = new Config();
                $options->protocol = 'https';
                $options->gatewayHost = 'openapi.alipay.com';
                $options->signType = 'RSA2';
                $options->appId = config('alipay_config')['app_id'];
                // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
                $options->merchantPrivateKey = config('alipay_config')['merchantPrivateKey'];
                $options->alipayCertPath = '';
                $options->alipayRootCertPath = '';
                $options->merchantCertPath = '';
                //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
                $options->alipayPublicKey = config('alipay_config')['alipayPublicKey'];
                //可设置异步通知接收服务地址（可选）
                $options->notifyUrl = $_SERVER['REQUEST_SCHEME'] .'://'. $_SERVER['HTTP_HOST'] . '/api/alipay/alinotify';
                //可设置AES密钥，调用AES加解密相关接口时需要（可选）
                $options->encryptKey = "";
                Factory::setOptions($options);
                $out_refund_no = 'r' . create_unique_number();
                $pay_price = strval($order_exist['pay_price']);
                $result = Factory::payment()->common()
                    ->batchOptional([
                        'out_request_no'=>$out_refund_no,
                        'refund_reason' => '给老子退钱'
                    ])
                    ->refund($pay_order_sn, $pay_price);
                mylog($this->cmd,var_export($this->object2array($result),true),'ali_refund.log');
                $responseChecker = new ResponseChecker();
                if (!$responseChecker->success($result)) {
                    return ajax($result->msg."，".$result->subMsg,-1,$result->msg."，".$result->subMsg);
                }
                Db::table('mp_food_order')->where($whereOrder)->update([
                    'refund' => 2,
                    'refund_no' => $out_refund_no,
                    'refund_apply_time' => time(),
                    'refund_time' => time()
                ]);
            }
        } catch (\Exception $e) {
            mylog($this->cmd,$e->getMessage());
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }
    //改变打印状态
    public function orderPrinted() {
        $order_id = input('post.order_id','');
        if(!$order_id) {
            return ajax('请传入订单id',-2);
        }
        $where = [
            ['status','=',1],
            ['is_print','=',0]
        ];
        $order_ids = [];
        if(is_string($order_id) || is_int($order_id)) {
            $order_ids = [$order_id];
        }
        if(is_array($order_id)) {
            $order_ids = $order_id;
        }
        $where[] = ['id','in',$order_ids];
        try {
            $res = Db::table('mp_food_order')->where($where)->update(['is_print'=>1]);
        } catch (\Exception $e) {
            return ajax($e->getMessage(), -1);
        }
        return ajax($res);
    }
    //获取今日未打印订单
    public function todayOrderList() {
        $shop_ids = input('post.shop_ids',[]);
        $whereOrder = [
            ['status','=',1],
            ['is_print','=',0],
            ['shop_id','in',$shop_ids],
            ['pay_time','>=',strtotime(date('Y-m-d 00:00:00'))],
            ['shop_id','in',$shop_ids],
        ];
        try {
            $order_list = Db::table('mp_food_order')->alias('o')
                ->where($whereOrder)
                ->order(['o.id'=>'DESC'])
                ->limit(0,200)
                ->field('id,pay_order_sn,pay_price,create_time,pay_time,shop_name,table_no,number,desc')
                ->select();
            if(!empty($order_list)) {
                $order_ids = [];
                foreach ($order_list as $order) {
                    $order_ids[] = $order['id'];
                }
                $whereDetail = [
                    ['order_id','in',$order_ids]
                ];
                $detail_list = Db::table('mp_food_order')->alias('o')
                    ->join('mp_food_order_detail d','o.id=d.order_id','left')
                    ->field('d.order_id,d.food_name,d.num,d.unit_price,d.total_price')
                    ->where($whereDetail)
                    ->select();
            }else {
                $detail_list = [];
            }
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        $ret = [
            'order_list' => $order_list,
            'detail_list' => $detail_list
        ];
        return ajax($ret);
    }
    //

    public function object2array(&$object) {
        if (is_object($object)) {
            $arr = (array)($object);
        } else {
            $arr = &$object;
        }
        if (is_array($arr)) {
            foreach($arr as $varName => $varValue){
                $arr[$varName] = $this->object2array($varValue);
            }
        }
        return $arr;
    }

    private function getMyShopIds($admin_id) {
        $where = [
            ['admin_id','=',$admin_id]
        ];
        $shop_ids = Db::table('mp_shop')->where($where)->column('id');
        return $shop_ids;
    }




}